package com.myapp.ruyixing.ui.widget;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;

public class PhotoPickFragment extends Fragment {

	public static interface PhotoPickCompleteListener {
		public void onPhotoPicker(String file);
	}

	private File mCameraSavedFile;

	private PhotoPickCompleteListener mPhotoPickCompleteListener;

	public static final PhotoPickFragment getInstance(int type) {
		PhotoPickFragment fragment = new PhotoPickFragment();
		Bundle bundle = new Bundle();
		bundle.putInt("type", type);
		fragment.setArguments(bundle);

		return fragment;
	}

	private void callCamera(int requestCode) {
		Intent intent = getCameraIntent();
		try {
			startActivityForResult(intent, requestCode);
		} catch (ActivityNotFoundException e) {
			e.printStackTrace();
		}
	}

	private Intent getCameraIntent() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		mCameraSavedFile = getOutputMediaFile();
		Uri fileUri = Uri.fromFile(mCameraSavedFile);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

		return intent;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK) {
			switch (requestCode) {
			case 1:
				complete(mCameraSavedFile.toString());
				break;
			case 2:
				Uri uri = data.getData();
				Cursor cursor = getActivity()
						.getContentResolver()
						.query(uri,
								new String[] { android.provider.MediaStore.Images.ImageColumns.DATA },
								null, null, null);
				cursor.moveToFirst();

				// Link to the image
				final String imageFilePath = cursor.getString(0);
				cursor.close();
				
				complete(imageFilePath);

				break;

			default:
				break;
			}
		}

		finish();
	}

	private static File getOutputMediaFile() {
		// To be safe, you should check that the SDCard is mounted
		// using Environment.getExternalStorageState() before doing this.

		File mediaStorageDir = new File(
				Environment
						.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
				"MyCameraApp");
		// This location works best if you want the created images to be shared
		// between applications and persist after your app has been uninstalled.

		// Create the storage directory if it does not exist
		if (!mediaStorageDir.exists()) {
			if (!mediaStorageDir.mkdirs()) {
				return null;
			}
		}

		// Create a media file name
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
				.format(new Date());
		File mediaFile = new File(mediaStorageDir.getPath() + File.separator
				+ "IMG_" + timeStamp + ".jpg");

		return mediaFile;
	}

	private void pickPhotoFromGallery(int requestCode) {
		Intent intent = new Intent();
		intent.setType("image/*");
		intent.setAction(Intent.ACTION_GET_CONTENT);
		startActivityForResult(Intent.createChooser(intent, "Select Picture"),
				requestCode);
	}
	
	private void complete(String url) {
		if (mPhotoPickCompleteListener != null) {
			mPhotoPickCompleteListener
					.onPhotoPicker(url);
		}
		
		finish();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		int type = getArguments().getInt("type");
		if (type == 1) {
			callCamera(1);
		} else if (type == 2) {
			pickPhotoFromGallery(2);
		}
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);

		if (getActivity() instanceof PhotoPickCompleteListener) {
			mPhotoPickCompleteListener = (PhotoPickCompleteListener) getActivity();
		}
	}

	private void finish() {
		getFragmentManager().beginTransaction().remove(this).commit();
	}
}
